/**
 * 
 */
package com.app.gameserver;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

import com.app.db.DBPool;
import com.app.framework.AbstractServer;
import com.app.framework.config.ActionConfigLoader;
import com.app.framework.config.PropConfigLoader;
import com.app.framework.config.ServiceConfigLoader;
import com.app.framework.handler.GameUpstreamHandler;
import com.app.framework.pipelinefactory.GamePipelineFactory;
import com.app.framework.pipelinefactory.HttpPipelineFactory;
import com.app.gameserver.http.HttpUpstreamHandler;
import com.app.server.QueueRunnable;
import com.app.service.item.itemspec.ItemSpecManager;

/**
 * @author lisong
 * @version 2013-2-26 下午2:41:32
 */
public class HttpServer extends AbstractServer {

	private HttpServer() {
		
	}
	
	public static void start() throws Exception {
		
		ServiceConfigLoader.getInstance();
			
		ActionConfigLoader.getInstance();
		
		PropConfigLoader.getInstance();
		
		ItemSpecManager.getInstance();
		
		ServerBootstrap bootstrap=new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
		
		GamePipelineFactory factory = new HttpPipelineFactory(new HttpUpstreamHandler(GameUpstreamHandler.HANDLER_TYPE_CS));
		
		bootstrap.setPipelineFactory(factory);
		 
		int port = Integer.parseInt(PropConfigLoader.getInstance().getConfig("httpport").getValue());

		bootstrap.setOption("child.tcpNoDelay", true);//child的属性 是与客户端建立连接的socket的,非child的是服务器负责监听客户端连接的主serversocket的
		
		bootstrap.setOption("child.receiveBufferSize", 1048576);
		// Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the "accept" queue can be. 
		//If this option is not configured, then the backlog depends on OS setting.
		bootstrap.setOption("backlog", 2000);
		
		Channel c = bootstrap.bind(new InetSocketAddress(port));
//		c.getConfig().setBufferFactory(HeapChannelBufferFactory.getInstance(ByteOrder.LITTLE_ENDIAN));//默认大头,在此可设置
		
		System.out.println("http start on "+port);
	}
	
	public static void main(String[] args) {
		try {
			HttpServer.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
			@Override
			public void run() {
				DBPool.getInstance().close();
			}
		}));
	}
}
